package cn.touna.jss.common.config;


import cn.touna.jss.common.properties.config.ScheduleCronProperties;
import cn.touna.jss.modules.custom.carmodel.synctask.SyncCarModelTask;
import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

import java.io.IOException;


@Configuration
public class ScheduleConfiguration {

    @Autowired
    private ScheduleCronProperties cronConf;

    @Bean
    public SpringBeanJobFactory jobFactory(ApplicationContext applicationContext) {
        AutoWiringSpringBeanJobFactory jobFactory = new AutoWiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean(name = "syncCarModelSchechulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean2(JobFactory jobFactory,
                                                      @Qualifier("syncCarModelTrigger") Trigger failDataTrigger
    ) throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setOverwriteExistingJobs(true);
        factory.setAutoStartup(true);
        factory.setStartupDelay(20);
        factory.setJobFactory(jobFactory);
        factory.setTriggers(failDataTrigger);
        return factory;
    }

    @Bean(name = "syncCarModelTask")
    public JobDetailFactoryBean failDataTaskDetail2() {
        return createJobDetail(SyncCarModelTask.class);
    }


    @Bean(name = "syncCarModelTrigger")
    public CronTriggerFactoryBean failDataTrigger2(@Qualifier("syncCarModelTask") JobDetail jobDetail) {
        return createCronTrigger(jobDetail, cronConf.getSyncModelCron());
    }

    private JobDetailFactoryBean createJobDetail(Class<?> jobClass) {
        JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
        factoryBean.setJobClass(jobClass);
        factoryBean.setDurability(true);
        return factoryBean;
    }

    private CronTriggerFactoryBean createCronTrigger(JobDetail jobDetail, String cronExpression) {
        CronTriggerFactoryBean factoryBean = new CronTriggerFactoryBean();
        factoryBean.setJobDetail(jobDetail);
        factoryBean.setCronExpression(cronExpression);
        factoryBean.setMisfireInstruction(SimpleTrigger.MISFIRE_INSTRUCTION_FIRE_NOW);
        return factoryBean;
    }
}
